<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;

//==========================================
//	ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {

    if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }

    if (!is_numeric($value)) {
        $value = "'" . mysql_real_escape_string($value, $handle) . "'";
    }
    return $value;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $uname = $_POST['username'];
    $pword = $_POST['password'];

    $uname = htmlspecialchars($uname);
    $pword = htmlspecialchars($pword);

    //==========================================
    //	CONNECT TO THE LOCAL DATABASE
    //==========================================
    $user_name = "root";
    $pass_word = "haddons";
    $database = "PPI";
    $server = "127.0.0.1";

    $db_handle = mysql_connect($server, $user_name, $pass_word);
    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {

        $q_uname = quote_smart($uname, $db_handle);
        $q_pword = quote_smart($pword, $db_handle);

        $SQL = "SELECT authorised FROM users WHERE login_ID = $q_uname AND password = md5($q_pword)";
        $result = mysql_query($SQL);
        $num_rows = mysql_num_rows($result);

        //====================================================
        //	CHECK TO SEE IF THE $result VARIABLE IS TRUE
        //====================================================

        if ($result) {
            if ($num_rows > 0) {
                $db_field = mysql_fetch_assoc($result);
                $authd = $db_field['authorised'];
                if ($authd) {
                    session_start();
                    $_SESSION['login'] = $uname;
                    //print $_SESSION['login'] . " logged on<br>";
                    header("Location: index.php");
                } else {
                    $errorMessage = "Login not yet authorised - please speak with System Administrator";
                }
            } else {
                //$errorMessage = "Invalid Login";
                //session_start();
                //$_SESSION['login'] = '';

                session_start();
                $_SESSION['login'] = "";
                header("Location: signup.php");
            }
        } else {
            $errorMessage = "Error logging on";
        }

        mysql_close($db_handle);
    } else {
        $errorMessage = "Error logging on";
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="./css/main.css" type="text/css">
    </head>
    <body>
<?PHP
//include 'i_head.html';
include 'i_loginForm.html';
include 'i_foot.html';
?>

        <?PHP print $errorMessage; ?>
